<?php

function fertilization_edit_page() {
  return drupal_get_form('fertilization_edit_form');
}

function fertilization_edit_form($form, &$form_state) {
  @$plant_info_id = $_GET['plant_info_id'];
  @$soil_info_id = $_GET['soil_info_id'];
  @$id = $_GET['id'];

  if (!empty($plant_info_id)) {
    $form_state['table_name'] = 'fertilization_info';
    $form_state['pid_name'] = 'plant_info_id';
    $form_state['pid_value'] = $plant_info_id;
  } elseif (!empty($soil_info_id)) {
    $form_state['table_name'] = 'fertilizer_recommendation';
    $form_state['pid_name'] = 'soil_info_id';
    $form_state['pid_value'] = $soil_info_id;
  } else{
    drupal_set_message(t('错误的参数！'), 'status', FALSE);
    drupal_goto('farmer/list');
  }
  $form_state['id'] = $id;

  if (!empty($id)) {
    $record = fertilization_load($form_state['table_name'], $form_state['pid_name'], $form_state['pid_value'], $id);
    if (empty($record)) {
      drupal_set_message(t('施肥信息不存在！'), 'status', FALSE);
      drupal_goto("farmer/fertilization/add", array('query' => array($form_state['pid_name']=>$form_state['pid_value'])));
    }
  }
  if (!empty($plant_info_id)) {
    $query = db_select( 'plant_info', 'T');
    $query->join('plant', 'P', 'P.plant_id=T.plant_id');
    $query->addField('P', 'plant_name');
  } else{
    $query = db_select( 'soil_info', 'T');
  }
  $query->join('farmer', 'F', 'F.farmer_id=T.farmer_id');
  $query->join('addr', 'A', 'F.addr_id=A.addr_id');
  $query->condition('T.'. $form_state['pid_name'], $form_state['pid_value'], '=');
  $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
  $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
  $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
  $query->addField('A1', 'name', 'province');
  $query->addField('A2', 'name', 'city');
  $query->addField('A3', 'name', 'county');
  $query->addField('F', 'farmer_name');
  $result = $query->execute()->fetchObject();

  $form['province'] = array(
    '#type' => 'textfield',
    '#default_value' => $result->province,
    '#size' => 32,
    '#maxlength' => 32,
    '#disabled' => TRUE,
  );
  $form['city'] = array(
    '#type' => 'textfield',
    '#default_value' => $result->city,
    '#size' => 32,
    '#maxlength' => 32,
    '#disabled' => TRUE,
  );
  $form['county'] = array(
    '#type' => 'textfield',
    '#default_value' => $result->county,
    '#size' => 32,
    '#maxlength' => 32,
    '#disabled' => TRUE,
  );
  $form['farmer'] = array(
    '#type' => 'textfield',
    '#title' => '农户名称',
    '#default_value' => $result->farmer_name,
    '#size' => 32,
    '#maxlength' => 32,
    '#disabled' => TRUE,
  );
  if (!empty($plant_info_id)) {
    $form['plant'] = array(
      '#type' => 'textfield',
      '#title' => '作物名称',
      '#default_value' => $result->plant_name,
      '#size' => 32,
      '#maxlength' => 32,
      '#disabled' => TRUE,
    );
  }

  $form['fertilization'] = array(
    '#type' => 'fieldset',
    '#title' => '施肥信息',
    '#collapsed' => false,
    '#collapsible' => true,
  );

  $type_options = array('基肥' => '基肥', '追肥' => '追肥');
  $form['fertilization']['type'] = array(
    '#type' => 'radios',
    '#default_value' => !empty($record) ? $record->type : '基肥',
    '#options' => $type_options,
  );

  $form['fertilization']['fertilizer_name'] = array(
    '#type' => 'textfield',
    '#title' => '肥料名称',
    '#default_value' => !empty($record) ? $record->fertilizer_name : '',
    '#size' => 32,
    '#maxlength' => 20,
  );

  $form['fertilization']['fertilizer_quantity'] = array(
    '#type' => 'textfield',
    '#title' => '用量（千克/亩）',
    '#default_value' => !empty($record) ? $record->fertilizer_quantity : 0,
//    '#size' => 32,
//    '#maxlength' => 8,
  );

  $form['fertilization']['fertilization_date'] = array(
    '#title' => '施肥日期',
    '#type' => 'metercomm_date',
    '#default_value' => _date_db_2_form(!empty($record) ? $record->fertilization_date : ''),
  );

  $form['fertilization']['fertilization_method'] = array(
      '#type' => 'textfield',
      '#title' => '施肥方法',
      '#default_value' => !empty($record) ? $record->fertilization_method : '',
      '#cols' => 32,
      '#rows' => 2,
      '#maxlength' => 50,
  );

  $form['fertilization']['comments'] = array(
      '#type' => 'textarea',
      '#title' => '备注',
      '#default_value' => !empty($record) ? $record->comments : '',
      '#cols' => 32,
      '#rows' => 2,
      '#maxlength' => 50,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => '提交',
    '#access' => fertilization_edit_form_submit_access($form_state, $id),
  );
  return $form;
}

function fertilization_edit_form_validate($form, &$form_state) {
  if(!empty($form_state['values']['fertilizer_quantity'])){
    $reg = '/^\d{1,8}(.\d{0,2})?$/';
    if(!preg_match ($reg, $form_state['values']['fertilizer_quantity']) || (strlen(explode('.',$form_state['values']['fertilizer_quantity'])[0])>8)) {
      form_set_error('fertilizer_quantity', "用量格式错误");
    }
  }
}

function fertilization_edit_form_submit($form, &$form_state) {
  global $user;

  if (empty($form_state['id'])) {
    $nid = db_insert($form_state['table_name'])
      ->fields(array(
        $form_state['pid_name'] => $form_state['pid_value'],
        'type' => $form_state['values']['type'],
        'fertilizer_name' => $form_state['values']['fertilizer_name'],
        'fertilization_date' => _date_form_2_db($form_state['values']['fertilization_date']),
        'fertilization_method' => $form_state['values']['fertilization_method'],
        'fertilizer_quantity' => _empty_2_zero($form_state['values']['fertilizer_quantity']),
        'comments' => $form_state['values']['comments'],
        'author_uid' => $user->uid,
        'timestamp' => time(),
      ))
      ->execute();
    if ($nid > 0) {
      drupal_set_message(t('添加成功！'), 'status', FALSE);
    }
    drupal_goto("farmer/fertilization/list", array('query' => array($form_state['pid_name']=>$form_state['pid_value'])));
  }
  else {
    $nid = db_update($form_state['table_name'])
      ->fields(array(
        'type' => $form_state['values']['type'],
        'fertilizer_name' => $form_state['values']['fertilizer_name'],
        'fertilization_date' => _date_form_2_db($form_state['values']['fertilization_date']),
        'fertilization_method' => $form_state['values']['fertilization_method'],
        'fertilizer_quantity' => _empty_2_zero($form_state['values']['fertilizer_quantity']),
        'comments' => $form_state['values']['comments'],
        'author_uid' => $user->uid,
        'timestamp' => time(),
      ))
      ->condition('id', $form_state['id'], '=')
      ->execute();
    if ($nid > 0) {
      drupal_set_message(t('修改成功！'), 'status', FALSE);
    }
    drupal_goto("farmer/fertilization/edit", array('query' => array($form_state['pid_name']=>$form_state['pid_value'])));
  }
}

function fertilization_edit_form_submit_access(&$form_state, $id) {
  global $user;
  $fertilization = fertilization_load($form_state['table_name'], $form_state['pid_name'], $form_state['pid_value'], $id);

  if ($fertilization) {
    $user_info = _get_user_info($user->uid);
    if ($fertilization->author_uid == $user->uid|| $user_info['role'] === 'administrator') {
      return TRUE;
    }
    else {
      return FALSE;
    }
  }
  else {
    //load false
    return user_access('edit farmer');
  }
}

function fertilization_load($table_name, $pid_name, $pid_value, $id) {
  $result = db_select($table_name, 'R')
    ->fields('R')
    ->condition('R.'.$pid_name, $pid_value, '=')
    ->condition('R.id', $id, '=')
    ->execute()
    ->fetchObject();
  return $result;
}

